<template>
  <div class="wrap-container">
    <CommonTreeMain
      ref="leftTreeRef"
      :query-form="treeQueryForm"
      :url="option.treeConfig.treeUrl"
      @handle-node-click="onNodeClick"
    >
      <template #main>
        <el-scrollbar :height="mainHeight">
          <div>
            <CommonForm
              ref="formRef"
              v-model="form"
              v-loading="option.treeConfig.isMainLoading"
              :layout-config="option.layoutConfig"
              :option="option"
              @on-extend-validate="onHandleExtendValidate"
              @on-submit="onhandleSubmit"
              @on-success="onHandleSucess"
            >
              <template #formHeader>
                <vab-query-form>
                  <vab-query-form-top-panel :span="16">
                    <el-button
                      v-show="!option.treeConfig.isShow"
                      v-permissions="{ permission: ['add:MenuList'] }"
                      :icon="Plus"
                      type="primary"
                      @click="onAdd"
                    >
                      添加
                    </el-button>
                    <el-button
                      v-show="!option.treeConfig.isShow"
                      v-permissions="{ permission: ['update:MenuList'] }"
                      :icon="Edit"
                      type="primary"
                      @click="onEdit()"
                    >
                      修改
                    </el-button>
                    <el-button v-show="option.treeConfig.isShow" type="primary" @click="onSave"> 保存 </el-button>
                    <el-button v-show="option.treeConfig.isShow" @click="onCancel"> 取消 </el-button>
                    <el-button
                      v-show="!option.treeConfig.isShow"
                      v-permissions="{ permission: ['del:MenuList'] }"
                      :icon="Delete"
                      type="danger"
                      @click="onDelete"
                    >
                      删除
                    </el-button>

                    <export-direct
                      v-show="!option.treeConfig.isShow"
                      v-permissions="{ permission: ['export:MenuList'] }"
                      expfilename="机构档案导出模板"
                      :params="exportParams"
                      url="office"
                    >
                      <template #downloadLink>
                        <el-button :icon="Download" style="margin-top: -10px; margin-left: 12px" type="primary"> 导出 </el-button>
                      </template>
                    </export-direct>

                    <el-button
                      v-show="!option.treeConfig.isShow"
                      v-permissions="{ permission: ['update:MenuList'] }"
                      :icon="CopyDocument"
                      type="success"
                      @click="onCopy()"
                    >
                      复制
                    </el-button>
                  </vab-query-form-top-panel>
                </vab-query-form>
              </template>
              <template #iconSlot>
                <SelectIcon v-model:icon-value="form.icon" />
              </template>
            </CommonForm>
          </div>
          <el-tabs v-model="activeName">
            <el-tab-pane label="按钮信息" name="first">
              <KingTable ref="kingTable" :tableOptions="_tableOptions" @handle-btn-click="handleBtnAction">
                <!-- 表格操作 -->
                <template #operation="scope">
                  <TableRowBtns :row="scope.row" @handle-row-action="handleBtnAction" />
                  <el-button type="primary" size="small" @click="handleBtnAction(operateType.EDIT, scope.row)"> 编辑 </el-button>
                  <el-button type="danger" size="small" @click="handleBtnAction(operateType.DEL, scope.row)"> 删除 </el-button>
                </template>
              </KingTable>
              <MenuResEdit ref="editRef" @on-success="fetchTableData" />
            </el-tab-pane>
          </el-tabs>
        </el-scrollbar>
      </template>
    </CommonTreeMain>
  </div>
</template>

<script setup lang="tsx" name="MenuList">
import { Plus, Delete, Edit, Download, CopyDocument } from "@element-plus/icons-vue";
import ExportDirect from "@/plugins/export/ExportDirect.vue";
import CommonTreeMain from "@/plugins/tree/CommonTreeMain.vue";
import { TableColumnOrFormTypeEnum } from "@/plugins/commonType.enum";
import { handleAdd, handleEdit, handleDelete, handleCancel, handleSave, handleNodeClick } from "@/plugins/tree/CommonTreeMainTs";
import CommonForm from "@/plugins/form/CommonForm.vue";
import KingTable from "@/components/KingTable/index.vue";
import { operateType } from "@/plugins/commonType.enum";
import { backTableHeight, postRequest } from "@/api/mains";
import MenuResEdit from "./components/MenuResEdit.vue";
import SelectIcon from "@/components/SelectIcon/index.vue";
import { failMsg, confirm } from "@/utils/MessageUtils";

//弹框高度
const mainHeight = ref(backTableHeight() + 175);
const formRef = ref();
const leftTreeRef = ref();
const treeQueryForm = ref({ EQ_ss: "1", IN_menutype: "M,C,R", pageSize: -1, sorts: "showorder@asc" });
const exportParams = ref({ EQ_ss: "1" });

const activeName = ref("first");

const onAdd = () => {
  handleAdd(option, formRef, form);
};
const onDelete = () => {
  handleDelete(option, form, leftTreeRef);
};
const onEdit = () => {
  handleEdit(option, form);
};

const onCopy = () => {
  if (_initParam.menuid == null || _initParam.menuid == "") {
    failMsg("请选择节点");
    return;
  }

  confirm("确定要复制菜单吗", async () => {
    const { code, msg, data }: { code: number; msg: string; data: any } = await postRequest("system/menu/copy", {
      id: _initParam.menuid
    });
    if (code == 200) {
      leftTreeRef.value.handleRefreshTree(data.id);
    } else {
      failMsg(msg);
    }
  });
};

const onSave = () => {
  formRef.value.onhandleSubmit();
};

const onCancel = async () => {
  handleCancel(option, formRef, form);
};

const onNodeClick = (treeNodeId: string) => {
  handleNodeClick(option, treeNodeId, form);
  _initParam.menuid = treeNodeId;
  fetchTableData();
};

const option = ref();
const form = ref({
  id: "",
  parentid: "",
  nodecode: "",
  nodename: "",
  icon: "",
  memo: ""
});
option.value = {
  treeConfig: {
    treeUrl: "system/menu/query", //左边树请求url
    entityUrl: "system/menu", //操作实体请求url
    isShow: false,
    disabled: true,
    editable: false,
    labelPosition: "right",
    id: "", //树节点的id
    parentid: "", //父节点id
    isMainLoading: false
  },
  layoutConfig: {
    column: 2,
    columnGap: "35px",
    pageBtnTabPosition: "left"
  },
  column: [
    {
      label: "上级节点",
      prop: "parentname",
      type: TableColumnOrFormTypeEnum.INPUT,
      disabled: true,
      placeholder: "请选择上级",
      expand: 2
    },
    {
      label: "菜单类别",
      prop: "menutype",
      type: TableColumnOrFormTypeEnum.SELECT,
      dictCode: "MenuType",
      placeholder: "请选择菜单类别",
      expand: 1
    },
    {
      label: "显示图标",
      prop: "icon",
      type: TableColumnOrFormTypeEnum.SLOT,
      slotName: "iconSlot",
      placeholder: "请输入显示图标",
      expand: 1
    },
    {
      label: "菜单显示名称",
      prop: "nodename",
      type: TableColumnOrFormTypeEnum.INPUT,
      placeholder: "请输入菜单显示名称",
      expand: 1
    },
    {
      label: "路由名称",
      prop: "name",
      type: TableColumnOrFormTypeEnum.INPUT,
      placeholder: "请输入路由名称",
      expand: 1
    },
    {
      label: "访问路径",
      prop: "path",
      type: TableColumnOrFormTypeEnum.INPUT,
      placeholder: "请输入路由路径"
    },
    {
      label: "组件路径",
      prop: "component",
      type: TableColumnOrFormTypeEnum.INPUT,
      placeholder: "请输入组件路径"
    },
    {
      label: "权限编码",
      prop: "perms",
      type: TableColumnOrFormTypeEnum.INPUT,
      placeholder: "请输入权限编码,如system:user:add"
    },
    {
      label: "是否固定",
      prop: "isAffix",
      type: TableColumnOrFormTypeEnum.SELECT,
      dictCode: "WhetherEnum",
      placeholder: "请选择是否固定",
      expand: 1
    },
    {
      label: "显示顺序",
      prop: "showorder",
      type: TableColumnOrFormTypeEnum.INPUTNUMBER,
      placeholder: "请输入显示顺序",
      precision: 0,
      min: 1,
      max: 999
    },
    {
      label: "备注",
      prop: "memo",
      type: TableColumnOrFormTypeEnum.TEXTAREA,
      placeholder: "请输入备注",
      expand: 2
    }
  ],
  formConfig: {
    title: "",
    labelPosition: "right",
    labelWidth: "120px",
    isInModal: false,
    disabled: true
  },
  btnsConfig: {
    save: {
      isShow: false
    },
    back: {
      isShow: false
    }
  },
  rules: {
    parentid: [{ required: true, trigger: "blur", message: "请输入上级分类" }],
    nodecode: [
      {
        required: true,
        trigger: "blur",
        message: "请输入机构编码"
      },
      {
        min: 1,
        max: 50,
        message: "输入长度 1 至 50",
        trigger: "blur"
      }
    ],
    nodename: [
      {
        required: true,
        trigger: "blur",
        message: "请输入机构名称"
      },
      {
        min: 1,
        max: 50,
        message: "输入长度 1 至 50",
        trigger: "blur"
      }
    ],
    type: [{ required: true, trigger: "blur", message: "请选择机构类别" }],
    showorder: [{ required: true, trigger: "blur", message: "请输入显示顺序" }],
    memo: [
      {
        max: 200,
        message: "输入长度 1 至 200",
        trigger: "blur"
      }
    ]
  }
};

const onHandleExtendValidate = () => {
  option.value.isValidatePass = true;
};
const onhandleSubmit = () => {
  //没有传url，则自己提交
  handleSave(option, formRef, form, leftTreeRef);
};

const onHandleSucess = () => {
  //数据提交成功，抛出事件
  console.warn("sucess");
};

// 获取 KingTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const kingTable = ref();
const editRef = ref();

// 如果表格需要初始化请求参数，直接定义传给 KingTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const _initParam = reactive({ menuid: "", EQ_ss: 1 });

// 表格配置项
const _tableCols = [
  { type: "selection", fixed: "left", align: "center", width: 60 },
  { type: "index", label: "序号", align: "center", width: 60 },
  {
    prop: "path",
    label: "按钮编码",
    width: 140,
    overflow: true
  },
  {
    prop: "perms",
    label: "按钮权限",
    width: 200,
    overflow: true
  },
  {
    prop: "nodename",
    label: "按钮名称",
    width: 120
  },
  {
    prop: "memo",
    label: "备注",
    overflow: true
  },
  { prop: "operation", label: "操作", fixed: "right", width: 160 }
];

const _tableOptions = {
  title: "登录日志",
  maxHeight: backTableHeight(),
  pageable: false,
  queryAuto: false,
  queryUrl: "system/menu/menuRes/query",
  operUrl: "system/menu/menuRes",
  tableColumns: _tableCols,
  initParam: _initParam
};

/**
 * 增删查按钮执行的业务操作
 * @param {*} type 当前执行操作的类型
 * @param {*} row
 */
const handleBtnAction = async (type: string, row: any) => {
  switch (type) {
    case operateType.ADD: // 新增操作
      if (_initParam.menuid == null || _initParam.menuid == "") {
        failMsg("请选择节点");
        return;
      }
      editRef.value.showDialog({ parentid: _initParam.menuid, ...row }, type);
      break;
    case operateType.EDIT: // 编辑操作
      editRef.value.showDialog(row);
      break;
    case operateType.DETAIL: // 查询操作
      break;
    case operateType.DEL: // 删除操作
      kingTable.value?.handleDelete(row);
      break;
    case operateType.BATCH_DEL: // 批量删除操作
      kingTable.value?.handleBatchDelete();
      break;
  }
};

// 重新拉取表格数据
const fetchTableData = () => {
  kingTable.value?.getTableList();
};
</script>

<style lang="scss" scoped>
.wrap-container {
  position: relative;
  padding: 0 !important;
}

/* 修改两列显示不出问题 */
:deep() {
  .el-form-item {
    /* flex: 0 0 48% !important; */
    padding-right: 0 !important;
  }
}
</style>
